﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using RBAC.Web.Mapper;
using RBAC.Web.Models;
using RBAC.Web.Service;
using RBAC.Web.Utilities;

namespace RBAC.Web.Controllers
{
    public class PermissionController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ListPermission(int? page, string sort = "", string sortdir = "asc"
							, String PermissionNameSearch = ""
				        )    
		{
			//ถ้าตัวมันเป็นลูกของตัวอื่น ต้องทำการ clear ค่า TempData ของแม่ก่อน
							if (TempData["RoleId"] != null)
				{
					TempData.Remove("RoleId");
				}
						    if (TempData["RoleDescField"] != null)
				{
					TempData.Remove("RoleDescField");
				}
								if (TempData["RoleLookupField"] != null)
				{
					TempData.Remove("RoleLookupField");
				}
					
			// end clear ค่า TempData

			ListPermissionModel model = new ListPermissionModel();
            /*GetAllResponseModel<PermissionModel> temp = Search(new GetAllPermissionRequestModel()
            {
									 PermissionName = PermissionNameSearch,
						                    Sort = sort,
					SortType = sortdir == "asc" ? sType.ASC : sType.DESC
            });
            model.ListItems = temp.List;*/
            
            return View(model);
        }

        [HttpPost]
        public ActionResult ListPermission(string submitButton, string[] checkbox, ListPermissionModel input)
        {
            if (ModelState.IsValid)
            {
               switch(submitButton) {
                   case "Search" :
                        input.ListItems = PrepareSearch(input);                      
                        break;
                   default :
                        break;
               }
            }
            return View(input);
        }

		public ActionResult EditPermission(String PermissionName)
        {
            ServiceClient service = new ServiceClient();

            GetAllPermissionRequestDto objGet = new GetAllPermissionRequestDto()
            {
                EqPk = true,
				PermissionName = StringParser.GetValue<String>(PermissionName)
            };

            var list = service.GetAllPermission(objGet);
			PermissionModel resultModel = null;


			if (list.Data != null && list.Data.Count > 0)
			{
				PermissionDto resultDto = list.Data[0];
				resultModel = PermissionMapper.DtoToModel(resultDto);

				//Get One-to-many data data ของลูก
                // สร้าง method PrepareXXXSearch
							}

						SetupRegisterViewModel(resultModel);
            return View(resultModel);
		}

		[HttpPost]
				public ActionResult Update(PermissionModel inputModel
					, string Parent_RoleRoleCode,String PermissionName
				)
				{
										ImageClass IClass = new ImageClass();
			            if (ModelState.IsValid)
            {
                ServiceClient service = new ServiceClient();
                var output = service.UpdatePermission(PermissionMapper.ModelToDto(inputModel));
                var listDisplay = PrepareRetrunFromOperation(new ListPermissionModel(), output.Data, output.Status,
                        Utilities.MessageUtil.GetMessage(Operation.Edit, output.Status));

						
				 // เพิ่ม message แสดงในหน้าแม่
                TempData["PermissionMessage"] = listDisplay.Message;
                TempData["PermissionStatus"] = output.Status;
                if (output.Data != null)
                {
                    TempData["PermissionId"] = output.Data.Id;
                }
						if (String.IsNullOrEmpty(Parent_RoleRoleCode))
                    return View("ListPermission", listDisplay);
                else
                    return RedirectToAction("EditRole", "Role", new { RoleCode = Parent_RoleRoleCode });
		            }   
            else
            {
				//Get One-to-many data data ของลูก
                // สร้าง method PrepareXXXSearch
				                SetupRegisterViewModel(inputModel);
                return View("EditPermission", inputModel);
            }
					}

        public ActionResult Add()
        {
            PermissionModel model = new PermissionModel();
            SetupRegisterViewModel(model);

					//Set 1-to-meny value (ค่ามาจากแม่)
			if (TempData["RoleId"] != null)
            {
                int result;
                int.TryParse(TempData["RoleId"].ToString(), out result);
                model.Role = result;
			}
								if(TempData["RoleDescField"] != null)
				{
				model.RoleId = StringParser.GetValue<int>(TempData["RoleDescField"].ToString());
				}
								if(TempData["RoleLookupField"] != null)
				{
				model.RoleRoleCode = StringParser.GetValue<String>(TempData["RoleLookupField"].ToString());
				}
				
            return View("AddPermission", model);
        }

        [HttpPost]
				public ActionResult AddPermission(PermissionModel inputModel
					, string Parent_RoleRoleCode
				)
		        {
				            ImageClass IClass = new ImageClass();
		            if (ModelState.IsValid)
            {
                ServiceClient service = new ServiceClient();
                var output = service.AddPermission(PermissionMapper.ModelToDto(inputModel));
                var listDisplay = PrepareRetrunFromOperation(new ListPermissionModel(), output.Data, output.Status,
								  Utilities.MessageUtil.GetMessage(Operation.Add, output.Status));

				
          // เพิ่ม message แสดงในหน้าแม่
                TempData["PermissionMessage"] = listDisplay.Message;
                TempData["PermissionStatus"] = output.Status;
                if (output.Data != null)
                {
                    TempData["PermissionId"] = output.Data.Id;
                }
						if (String.IsNullOrEmpty(Parent_RoleRoleCode))
                    return View("ListPermission", listDisplay);
                else
                    return RedirectToAction("EditRole", "Role", new { RoleCode = Parent_RoleRoleCode });
		            }
            else
            {
                SetupRegisterViewModel(inputModel);
                return View(inputModel);
            }
                }

        [HttpPost]
        public string DeletePermissions(string[] PermissionCheckbox)
        {
            ListPermissionModel input = new ListPermissionModel();
            if (ModelState.IsValid)
            {
                input = Delete(PermissionCheckbox, input);
            }

            if(input.IsSuccessed.GetValueOrDefault(false))
                return Boolean.TrueString;
            else
                return Boolean.FalseString;
        }

        [HttpPost]
        public String DeletePermissionById(string Id)
        {
            List<string> delList = new List<string>();
            delList.Add(Id);
            ServiceClient service = new ServiceClient();
            var output = service.DeletePermission(delList);

			if (output.Status) 
			{ 
				foreach (string delListID in delList) 
				{ 
					if (System.IO.Directory.Exists(Server.MapPath("~/Image/Permission") + "\\" + delListID + "\\")) 
					{ 
						System.IO.DirectoryInfo DI = new System.IO.DirectoryInfo(Server.MapPath("~/Image/Permission") + "\\" + delListID + "\\"); DI.Delete(true); 
					} 
				} 
			}

			//แสดง message ให้ class แม่
            TempData["PermissionMessage"] = Utilities.MessageUtil.GetMessage(Operation.Delete, output.Status);
            TempData["PermissionStatus"] = output.Status;

            if (output.Status)
                return Boolean.TrueString;
            else
                return Boolean.FalseString;
           
        }

        // Check does PermissionName exist
        [HttpPost]
        public JsonResult doesPermissionNameExist(string PermissionName, string Mode, string OldValue)
        {
			bool callCheck = false;
            if (Mode.Equals("Add", StringComparison.OrdinalIgnoreCase))
            {
                callCheck = true;
            }
            else if (Mode.Equals("Edit", StringComparison.OrdinalIgnoreCase))
            {
                if (!OldValue.Trim().Equals(PermissionName.Trim(), StringComparison.OrdinalIgnoreCase))
                    callCheck = true;
            }

            if (callCheck)
            {
				var service = new ServiceClient();
                var exist = service.ExistPermission(PermissionName).Data;
                return Json(!exist);
            }
            else
                return Json(true);
        }

		#region private methods

        private ListPermissionModel Delete(string[] inputList, ListPermissionModel input)
        {
            List<string> delList = new List<string>();
			var listDisplay = new ListPermissionModel();
            if (inputList != null && inputList.Length > 0)
            {
                foreach (string id in inputList)
                {
                    delList.Add(id);
                }
                ServiceClient service = new ServiceClient();
                var output = service.DeletePermission(delList);
                listDisplay = PrepareRetrunFromOperation(input, output.Data, output.Status,
                        Utilities.MessageUtil.GetMessage(Operation.Delete, output.Status));

				if (output.Status) 
				{ 
					foreach (string inputListSplit in inputList) 
					{ 
						if (System.IO.Directory.Exists(Server.MapPath("~/Image/Permission") + "\\" + inputListSplit + "\\")) 
						{ 
							System.IO.DirectoryInfo DI = new System.IO.DirectoryInfo(Server.MapPath("~/Image/Permission") + "\\" + inputListSplit + "\\"); DI.Delete(true); 
						} 
					} 
				}

				TempData["PermissionMessage"] = listDisplay.Message;
                TempData["PermissionStatus"] = output.Status;
            }

            listDisplay.ListItems = PrepareSearch(listDisplay);
            return listDisplay;
        }

        private List<PermissionModel> PrepareSearch(ListPermissionModel input)
        {

            GetAllPermissionRequestModel searchInputs = new GetAllPermissionRequestModel()
            {
									PermissionName = (input.PermissionNameSearch == null) ? ""  : input.PermissionNameSearch,
						
							Sort = "PermissionName",
				SortType = sType.ASC
			};
            var result = Search(searchInputs);
            return result.List;
        }

        private GetAllResponseModel<PermissionModel> Search(GetAllPermissionRequestModel input)
        {
            ServiceClient service = new ServiceClient();
            GetAllPermissionRequestDto gAllreq = new GetAllPermissionRequestDto { 
		  							PermissionName = input.PermissionName,
		                   SortType = input.SortType.ToString(),
                 Sort = input.Sort
            };
            var response = service.GetAllPermission(gAllreq);
            var result = new GetAllResponseModel<PermissionModel>();
            result.List = new List<PermissionModel>();
            if(response != null)
            {
                if (response.Data != null && response.Data.Count > 0)
                {
                    foreach (PermissionDto responseDTO in response.Data)
                    {
                        PermissionModel resultModel = null;
                        PermissionDto tempDto = responseDTO;
                        resultModel = PermissionMapper.DtoToModel(tempDto);
                        result.List.Add(resultModel);
                    }
                }
            }
            return result;
        }

		private ListPermissionModel PrepareRetrunFromOperation(ListPermissionModel listModel, PermissionDto dto, bool status, string message)
		{
			if (status)
			{
				if (dto != null)
				{
					listModel.ListItems.Add(PermissionMapper.DtoToModel(dto));
				}
			}
			listModel.Message = message;
			listModel.IsSuccessed = status;
			return listModel;

		}



		
		private void SetupRegisterViewModel(PermissionModel model)
        {
            //เช็คว่ามี Attribute ที่เป็น DateTime ใน model หรือเปล่าถ้ามี + ปีไป 543 ถ้าปีเป็น ค.ศ.
            Utilities.Utilities.PrepareDateTimeProperity(model);
        }

		/// <summary>
        /// Name ::: Mr. Akawit Tangkupatanonth
        /// Date ::: 16/03/2014
        /// Description ::: This function for call validate method in validate class
        /// </summary>
        /// <returns>Boolean</returns>
		
		#endregion
    }
}
